import * as fs from 'fs';
import * as Busboy from 'busboy';
const config = require('../../config');
import * as uuid from 'uuid';
import * as moment from 'moment';
import FileService from '../services/file';

export default (app, router) => {
  router.get('/files/:dirname/:filename', async (req, res, next) => {
    const filePath = config.output_path + req.params.dirname + '/' + req.params.filename;
    if (fs.existsSync(filePath)) {
      fs.createReadStream(filePath).pipe(res);
    } else {
      res.status(404).send('Not found');
    }
  });

  router.post('/convert', (req, res, next) => {
    try {
      console.log('start upload');
      const key = uuid.v1().replace(/-/g, '') + '_' + moment().format('YYYYMMDDHHmmss');
      const busboy = new Busboy({headers: req.headers});
      busboy.on('file', (fieldName, file, extName, encoding, mimeType) => {
        const filePath = config.input_path + key + '.' + extName;
        file.pipe(fs.createWriteStream(filePath));
        file.on('data', (data) => {
        });
        file.on('end', async () => {
          console.log('end upload');
          await FileService.convertFile(filePath, extName);
          const outputPath = `files/${key}/${key}.mxl`;
          res.end(outputPath);
        });
      });
      req.pipe(busboy);
      busboy.on('finish', () => {
      });
    } catch (err) {
      console.log('upload error');
      res.end('');
    }
  });
};
